"use strict";

const config = require('config');
const mysqlConfig = config['mysql'];
const DbService	= require("moleculer-db");
const SqlAdapter = require("moleculer-db-adapter-sequelize");


module.exports = function(collection) {
	const cacheCleanEventName = `cache.clean.${collection}`;
	return {
		mixins: [DbService],
		adapter: new SqlAdapter(mysqlConfig["db"], mysqlConfig["user"], mysqlConfig["password"], {
			dialect: 'mysql',
			host: mysqlConfig["host"],
			port: mysqlConfig["port"],
			timezone: '+08:00',
			pool: {
				max: 5,
				min: 0,
				idle: 10000
			},
			logging: true,
		}),
		settings:{
			maxPageSize:999999999,
			pageSize:30,
		},
		actions:{
			attributes: {
				async handler() {
					return this.attributes();
				}
			},
			tableName: {
				async handler() {
					return this.tableName();
				}
			},
		},
		methods: {
			async entityChanged(type, json, ctx) {
				await this.clearCache();
				const eventName = `${this.name}.entity.${type}`;
				this.broker.emit(eventName, { meta: ctx.meta, entity: json });
			},
			tableName() {
				return this.adapter.model["getTableName"]();
			},
			attributes() {
				return this.adapter.model.rawAttributes;
			}
		},
		collection
	};
};
